package com.cn.por.config.security;

import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import com.cn.por.biz.menu.dto.MenuDto;
import com.cn.por.biz.menu.service.MenuService;


/**
 * 动态权限控制
 * @author wen
 *
 */
@Component
public class CustomSecurityMetaDataSource implements FilterInvocationSecurityMetadataSource {
	@Autowired
	private MenuService menuService;
	
	AntPathMatcher antPathMatcher = new AntPathMatcher();
	/**
	 * 这个方法会产生一个问题，当某个资源字符串没有纳入菜单管理，或者没有任何角色持有
	 * 该资源字符串时，访问不受限制。
	 */

	@Value("${server.servlet.context-path}")
	private String contextPath;
	
	@Override
	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
		String requestUrl = ((FilterInvocation) object).getRequest().getRequestURI();
		/**
		 * 获取系统所有角色对应的资源权限字符串
		 */
		List<MenuDto> menuList = menuService.getMenu();
		/**
		 * 获取持有该资源字符串的角色
		 */
		for(MenuDto menu : menuList) {
			if(antPathMatcher.match(menu.getPattern(), requestUrl.replace(contextPath, ""))) {
				String[] roles = menu.getRoles().stream().map(r -> r.getName()).toArray(String[]::new);
				return SecurityConfig.createList(roles);
			}
		}
		 return null;
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return FilterInvocation.class.isAssignableFrom(clazz);
	}

}
